import Vue from "vue";
import Vuex from "vuex";
import vuexPersist from "vuex-persistedstate";
Vue.use(Vuex);
import bill from "@/store/bill";
import { preRequest } from "@/api";

export default new Vuex.Store({
  state: {
    firstName: "zhang",
    lastName: "san",
    person: {
      name: "lisi",
      age: 10,
    },
    collapse: true,
    shoppingStateEnums: [],
    accounts: [],
    userinfo: "",
  },
  mutations: {
    updateFirstName(state, payload) {
      state.firstName = payload.split(" ")[0];
      state.lastName = payload.split(" ")[1];
    },
    switchCollapse(state) {
      state.collapse = !state.collapse;
    },
    shoppingStateEnums(state, payload) {
      state.shoppingStateEnums = payload;
    },
    updateUserInfo(state, payload) {
      state.userinfo = payload;
    },
  },
  actions: {
    axiosName(context, payload) {
      setTimeout(() => {
        context.commit("updateFirstName", payload);
      }, 1000);
    },
    axiosShoppingStates({ commit }) {
      // Vue.axios({
      //   method: "get",
      //   url: "http://localhost:9090/swimming/shopping/shoppingStates",
      // })
      preRequest.shoppingStates().then(
        (res) => {
          let s = ["info", "primary", "warning", "danger"];
          res.data.forEach((x) => {
            x.color = s.find((y, i) => i === x.index);
          });
          commit("shoppingStateEnums", res.data);
        },
        (error) => {
          console.log(" request error : " + error.response.status);
        }
      );
    },
  },
  // this.$store.state.firstName;
  // this.$store.mutations.updateFirstName();
  // this.$store.commit("updateFirstName")
  // this.$store.actions.axiosName()
  // this.$store.dispatch("axiosName")
  modules: {
    bill: bill,
  },
  plugins: [
    // vuex plugin[]
    vuexPersist({
      storage: window.sessionStorage,
      reducer: (state) => {
        return {
          collapse: state.collapse,
          billinfo: state.bill.info,
          firstName: state.firstName,
          lastName: state.lastName,
          shoppingStateEnums: state.shoppingStateEnums,
          accounts: state.accounts,
          userinfo: state.userinfo,
        };
      },
    }),
  ],
  getters: {},
});
